// pages/authorize/authorize.js
const base64 = require('../../utils/base64.js')
const common = require('../../utils/common.js')
const app = getApp()
Page({
  data: {
    //判断小程序的API，回调，参数，组件等是否在当前版本可用。
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    // sessionKey: "",
    avatarUrl: ""
  },
  onLoad: function(option) {
    var that = this
    // that.setData({
    //   sessionKey: option.session_key
    // })
    // 查看是否授权
    wx.getSetting({
      success: function(res) {
        if (res.authSetting['scope.userInfo']) {
          wx.getUserInfo({
            success: function(res) {
              console.log(option)
              console.log(res.userInfo)

              //调用登录接口
              wx.login({
                success: function (resLogin) {
                  console.log(resLogin)
                  console.log('调用登录接口wx.login成功')

                  if (resLogin.code) {
                    wx.request({
                      url: common.apiUrl() + 'jscode2session',
                      method: 'POST',
                      header: {
                        'content-type': 'application/x-www-form-urlencoded'
                      },
                      data: {
                        code: resLogin.code,
                        nickname: res.userInfo.nickName,
                        avatarurl: res.userInfo.avatarUrl,
                        gender: res.userInfo.gender,
                        province: res.userInfo.province,
                        city: res.userInfo.city,
                        country: res.userInfo.country
                      },
                      success: function (resCode2Session) {
                        console.log(resCode2Session.data.data)
                        // success
                        app.globalData.wangcaiToken = resCode2Session.data.data
                        wx.setStorageSync("wangcai_token", resCode2Session.data.data)

                        wx.navigateBack({
                          delta: 1
                        })
                        // 为获取用户唯一的unionid,来区分用户的唯一性
                        // wx.request({
                        //   url: common.apiUrl()+'decodeUserInfo',
                        //   data: {
                        //     encryptedData:resUserInfo.encryptedData,
                        //     iv:resUserInfo.iv,
                        //     sessionKey:resCode2Session.data.data.session_key
                        //   },
                        //   success: function(resDecodeUserInfo){
                        //     // success
                        //     console.log(resDecodeUserInfo.data)
                        //   }
                        // })
                      },
                      fail: function (e) {
                        console.log(e)
                      }
                    })
                  }
                }
              })

              // that.setData({
              //   avatarUrl: res.userInfo.avatarUrl
              // })
              // that.getWxLogin(res.encryptedData, res.iv)
              // that.clientGetToken()
            }
          });
        }
      }
    })
  },
  bindGetUserInfo: function(e) {
    if (e.detail.userInfo) {
      //用户按了允许授权按钮
      var that = this
      console.log(e.detail.userInfo)
      
      //调用登录接口
      wx.login({
        success: function (resLogin) {
          console.log(resLogin)
          console.log('调用登录接口wx.login成功')

          if (resLogin.code) {
            wx.request({
              url: common.apiUrl() + 'jscode2session',
              method: 'POST',
              header: {
                'content-type': 'application/x-www-form-urlencoded'
              },
              data: {
                code: resLogin.code,
                nickname: e.detail.userInfo.nickName,
                avatarurl: e.detail.userInfo.avatarUrl,
                gender: e.detail.userInfo.gender,
                province: e.detail.userInfo.province,
                city: e.detail.userInfo.city,
                country: e.detail.userInfo.country
              },
              success: function (resCode2Session) {
                console.log(resCode2Session.data.data)
                // success
                app.globalData.wangcaiToken = resCode2Session.data.data
                wx.setStorageSync("wangcai_token", resCode2Session.data.data)

                wx.navigateBack({
                  delta: 1
                })
                // 为获取用户唯一的unionid,来区分用户的唯一性
                // wx.request({
                //   url: common.apiUrl()+'decodeUserInfo',
                //   data: {
                //     encryptedData:resUserInfo.encryptedData,
                //     iv:resUserInfo.iv,
                //     sessionKey:resCode2Session.data.data.session_key
                //   },
                //   success: function(resDecodeUserInfo){
                //     // success
                //     console.log(resDecodeUserInfo.data)
                //   }
                // })
              }
            })
          }
        }
      })


      // that.setData({
      //   avatarUrl: e.detail.userInfo.avatarUrl
      // })
      // that.getWxLogin(e.detail.encryptedData, e.detail.iv)

    } else {
      //用户按了拒绝按钮
      wx.showModal({
        title: '警告',
        content: '您点击了拒绝授权，将无法获取小程序相关信息，请授权之后再进入!!!',
        showCancel: false,
        confirmText: '返回',
        success: function(res) {
          wx.switchTab({
            url: '/pages/smartlife/smartlife'
          })
        }
      })
    }
  },
  getWxLogin: function(encryptedData, ivStr) {
    var that = this
    var str = common.baseClient()
    var authKey = base64.base64encode(str)
    wx.login({
      success(res) {
        if (res.code) {
          // console.log(res.code)
          console.log(common.hostUrl() + '/wxLogin/' + res.code)
          // 发起网络请求
          wx.request({
            url: common.hostUrl() + '/wxLogin/' + res.code,
            // data: JSON.stringify({
            //   mobile: "13000000000",
            //   password: "123456"
            // }),
            header: {
              "Content-Type": "application/json",
              "Authorization": "Basic " + authKey
            },
            method: "GET",
            success: function(res) {
              console.log(res.data.data)
              console.log(authKey)
              if (res.data.data.flag) { //标签值flag=true，此微信第一次登录，调用getUserInfo获取基础数据

                console.log(res.data.data.result.sessionKey + encryptedData + ivStr)

                wx.request({
                  url: common.hostUrl() + '/wxLogin',
                  data: {
                    sessionKey: res.data.data.result.sessionKey,
                    encryptedData: encryptedData,
                    ivStr: ivStr
                  },
                  header: {
                    "Content-Type": "application/json",
                    "Accept": "*/*",
                    "Authorization": "Basic " + authKey
                  },
                  method: "POST",
                  success: function(res) {
                    console.log(res.data)
                    if (res.data.code == 0) {
                      //存储userinfo信息
                      try {
                        wx.setStorageSync('user_info', res.data.data)
                        //授权成功后，跳转回上一界面
                        wx.navigateBack({
                          delta: 1
                        })
                      } catch (e) {

                      }
                    } else {
                      wx.showToast({
                        title: res.data.message,
                        image: "/image/error.png"
                      })
                    }
                  }
                })

              } else {
                //有值，直接初始化数据
                wx.setStorageSync('user_info', res.data.data)
                //返回到之前界面
                var pages = getCurrentPages();
                if (pages.length > 1) {
                  //上一个页面实例对象
                  var prePage = pages[pages.length - 2];
                  prePage.onLoad()
                  console.log('调用成功---' + pages.length)
                }
                wx.navigateBack({
                  delta: 1
                })
              }
            }
          })
        } else {
          console.log('登录失败！' + res.errMsg)
        }
      }
    })


  },
  clientGetToken: function() {
    var that = this
    var str = common.baseClient()
    var authKey = base64.base64encode(str)
    wx.request({
      url: common.hostUrl() + '/client/token',
      data: JSON.stringify({
        mobile: "13000000000",
        password: "123456"
      }),
      header: {
        "Content-Type": "application/json",
        "Authorization": "Basic " + authKey
      },
      method: "POST",
      success: function(res) {
        console.log(res.data)
        if (res.data.code == 0) {
          //存储userinfo信息
          try {
            wx.setStorageSync('user_info', res.data.data)
            //获得用户收据后的一系列操作
            that.initData(res.data.data)
          } catch (e) {

          }
        }
      }
    })
  },
  cancelClick: function(e){
    wx.showModal({
      title: '警告',
      content: '您点击了拒绝授权，将无法获取小程序相关信息，请授权之后再进入!!!',
      showCancel: false,
      confirmText: '返回',
      success: function(res) {
        if (res.confirm) {
          console.log('用户点击了“返回授权”')
          wx.switchTab({
            url: '/pages/smartlife/smartlife'
          })
        }
      }
    })
  }

})